﻿CREATE FUNCTION [dbo].[SemiMonthlyPaymentSchedule](
	@FirstPmtDate datetime,
	@StartDate datetime,
	@Today datetime
)RETURNS  @T TABLE (PaymentDate datetime) WITH SCHEMABINDING AS BEGIN
-- TODO: If @StartDare is off the schedule - sckip one payment
DECLARE @Mos int
SET @Mos =
	CASE DATEPART(dd,@FirstPmtDate) 
				WHEN DATEPART(dd,@StartDate) THEN 1
				WHEN DATEPART(dd,@StartDate)+15 THEN 0
				ELSE -1 END

IF @Mos = -1 BEGIN
	SELECT @FirstPmtDate = dbo.MonthStart(@StartDate)+DATEPART(dd,@FirstPmtDate)-1,@Mos = 1
	SET @StartDate = @FirstPmtDate
END
ELSE
	SET @FirstPmtDate = @StartDate - CASE @Mos WHEN 1 THEN 0 ELSE -15 END

WHILE @StartDate <= @Today BEGIN
	INSERT INTO @T VALUES(@StartDate)
	SELECT @StartDate = DATEADD(dd,15*(@Mos%2),DATEADD(mm,@Mos/2,@FirstPmtDate)),
				 @Mos = @Mos + 1
END

RETURN
END


